package cn.kain.util;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

import org.apache.commons.dbcp.BasicDataSource;

public class DBTool {

	private static BasicDataSource ds;

	/**
	 * 测试数据库连接
	 * @param args
	 */
	public static void main(String args[]) {
		try {
			Connection conn = DBTool.getConnection();
			if (conn != null) {
				System.out.println("数据库连接成功！");
			} else {
				System.out.print("数据库连接失败！");
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	static {
		// 加载参数
		Properties p = new Properties();
		try {
			p.load(DBTool.class.getClassLoader().getResourceAsStream("db.properties"));
			// 获取这些参数
			String driver = p.getProperty("driver");
			String url = p.getProperty("url");
			String user = p.getProperty("username");
			String pwd = p.getProperty("password");
			String initialSize = p.getProperty("initialSize");
			String maxActive = p.getProperty("maxActive");
			// 创建连接池
			ds = new BasicDataSource();
			// 给它设置参数
			ds.setDriverClassName(driver);
			ds.setUrl(url);
			ds.setUsername(user);
			ds.setPassword(pwd);
			ds.setInitialSize(Integer.parseInt(initialSize));
			ds.setMaxActive(Integer.parseInt(maxActive));
		} catch (IOException e) {
			e.printStackTrace();
			throw new RuntimeException("加载db.properties失败", e);
		}
	}

	/**
	 * 由连接池创建的连接,其实现类由连接池提供.
	 */
	public static Connection getConnection() throws SQLException {
		return ds.getConnection();
	}

	/**
	 * 关闭连接
	 */
	public static void close(Connection conn) {
		if (conn != null) {
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
				throw new RuntimeException("归还连接失败", e);
			}
		}
	}

	/**
	 * 回滚事务
	 * @param conn
	 */
	public static void rollback(Connection conn) {
		if (conn != null) {
			try {
				conn.rollback();
			} catch (SQLException e) {
				e.printStackTrace();
				throw new RuntimeException("回滚事务失败", e);
			}
		}
	}

}
